package com.example.springboothello.websocket;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.client.WebSocketClient;
import org.springframework.web.socket.sockjs.client.SockJsClient;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

/**
 * @Author JC
 * @description TODO
 * @Date 2023-10-23 20:09
 * @Version 1.0
 */
@ServerEndpoint(value = "/api/websocket/{userId}")
@Slf4j
@Component
public class webSocketServer {

    public static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    private String userId;

    /**
     * 开启连接
     * @param session
     * @param userId
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("userId") String userId) {
        this.userId = userId;
        log.info("连接建立:{}",userId);
        String format = sdf.format(new Date());
        log.info("连接建立时间:{}",format);
    }

    @OnClose
    public void onClose() {
        log.info("连接关闭");
        String format = sdf.format(new Date());
        log.info("连接关闭时间:{}",format);
    }

    @OnMessage
    public void onMessage(String message,Session session) {
        try {
            // 向客户端返回消息
            session.getBasicRemote().sendText("消息收到");
            log.info("消息收到:{}",message);
        } catch (IOException e) {
            e.printStackTrace();
         }
    }



}
